//
//  BJPublishViewController.m
//  BowJoy
//
//  Created by  on 2024/5/13.
//

#import "BJPublishViewController.h"
#import "BJPushCollectionViewCell.h"
#import "BJTextView.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <Photos/PHPhotoLibrary.h>
#import<CTAssetsPickerController/CTAssetsPickerController.h>

@interface BJPublishViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextViewDelegate,BJPushCollectionViewCellDelegate,CTAssetsPickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *bgGroundView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UITextField *textFiled;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (nonatomic) NSInteger cellNumber;
@property (nonatomic) NSMutableArray *pictureArr;//用于存放图片

@property (nonatomic) NSMutableArray *fileNameArr;//用于上传的图片
@property (strong, nonatomic) BJTextView *editView;
@property (strong, nonatomic) NSString *imageUrl;


@end

@implementation BJPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UICollectionViewFlowLayout * layOut = [[UICollectionViewFlowLayout alloc]init];
    layOut.itemSize = CGSizeMake(90, 120);
    self.collectionView.collectionViewLayout = layOut;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BJPushCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BJPushCollectionViewCell"];
    
    [self.pictureArr addObject:@"icon_push_picture"];
    [self.collectionView reloadData];
    
    self.contentView.addChild(self.editView);
    self.editView.makeCons(^{
        make.leading.trailing.constants(0);
        make.top.constants(5);
        make.height.constants(180);
    });
    
    self.editView.currentText.text = [NSString stringWithFormat:@"%lu/500",(unsigned long)self.editView.textView.text.length];
 
    //埋点
    NSMutableArray *dataList = [NSMutableArray array];
    NSDictionary *dict = @{
        @"page":@"publish",
        @"duration":@(0),
        @"event":@"pv",
        @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
    };
    [dataList addObject:dict];
    [[BJNetManager shareNetManager]postLogWithParam:dataList];
        
    
}

-(void)saveAction{

    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

        if (status != PHAuthorizationStatusAuthorized) {
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            CTAssetsPickerController *assetPC = [[CTAssetsPickerController alloc]init];
            assetPC.showsEmptyAlbums=YES;
            assetPC.showsSelectionIndex=YES;
            assetPC.assetCollectionSubtypes = @[@(PHAssetCollectionSubtypeSmartAlbumUserLibrary), @(PHAssetCollectionSubtypeAlbumRegular)];
            assetPC.delegate=self;
            [self presentViewController:assetPC animated:YES completion:nil];
        });
    }];

}

#pragma mark - CTAssetsPickerControllerDelegate -

// 限定选择的最大选择个数

- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset{

      NSInteger max =3-self.cellNumber;
      if (picker.selectedAssets.count >= max) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Notice" message:[NSString stringWithFormat:@"Select up to %ld images", (long)max] preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault handler:nil]];
        [picker presentViewController:alert animated:YES completion:nil];
        return NO;
      }
      if (asset.mediaType == PHAssetMediaTypeVideo) {
        return NO; // 如果是视频，不显示该资源
      }

      return YES;

}
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldEnableAsset:(PHAsset *)asset{
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        return NO; // 如果是视频，不显示该资源
    }
      return YES;
}
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets{

    
    [picker dismissViewControllerAnimated:YES completion:nil];
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = PHImageRequestOptionsResizeModeExact;
    option.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    [ASHUD showASLoading];

    
    for (int i = 0; i<assets.count; i++) {
        PHAsset*asset = assets[i];
        CGSize asseSize = CGSizeMake(asset.pixelWidth / [UIScreen mainScreen].scale, asset.pixelHeight / [UIScreen mainScreen].scale);
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:asseSize contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            UIImage *newimg = [self compressOriginalImage:result toSize:CGSizeMake(0.01, 0.01)];
            [self.pictureArr addObject:newimg];
            self.cellNumber ++;
        }];
        
    }
        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ASHUD hideHUD];

        [self.pictureArr removeObject:@"icon_push_picture"];
        [self.pictureArr addObject:@"icon_push_picture"];
        [self.collectionView reloadData];
    });


}




- (BJTextView *)editView{
    AsGetMethodReturnObjc(_editView);
    _editView = [[BJTextView alloc]init];
    _editView.textView.delegate = self;
    return _editView;
}


- (NSMutableArray *)pictureArr{
    AsGetMethodReturnObjc(_pictureArr);
    _pictureArr = [NSMutableArray array];
    return _pictureArr;
}

- (NSMutableArray *)fileNameArr{
    AsGetMethodReturnObjc(_fileNameArr);
    _fileNameArr = [NSMutableArray array];
    return _fileNameArr;
}


#pragma mark --UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return  self.pictureArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID=@"BJPushCollectionViewCell";
    BJPushCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    if (indexPath.row == self.pictureArr.count-1){
        cell.logoIcon.image = [UIImage imageNamed:self.pictureArr[indexPath.row]];
        cell.deleteBtn.hidden = YES;
    }else{
        cell.logoIcon.image = self.pictureArr[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.indexRow = indexPath.row;
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == self.pictureArr.count-1) {
//        [self selectImage];
        [self saveAction];
    }
}


// 保存图片到沙盒
+ (NSString *)saveImageToDocuments:(UIImage *)image withName:(NSString *)imageName {
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0); // 将图片转换为JPEG格式的NSData
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", imageName]];
    
    [fileManager createFileAtPath:filePath contents:imageData attributes:nil];
    
    return filePath;
}
 
// 从沙盒中读取图片
+ (UIImage *)readImageFromDocumentsWithName:(NSString *)imageName {
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", imageName]];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage imageWithData:imageData];
    
    return image;
}

//-(void)selectImage{
//    TZImagePickerController *picturePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:3-self.cellNumber delegate:self];
//    picturePickerVC.allowPickingVideo = NO;
//    kWeakSelf(weakSelf)
//    picturePickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
//    [picturePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//
//        for(int i=0;i<photos.count;i++){
//            UIImage *newimg = [self compressOriginalImage:photos[i] toSize:CGSizeMake(0.01, 0.01)];
//            [weakSelf.pictureArr addObject:newimg];
//            self.cellNumber ++;
//            
//        }
//        for(int i=0;i<weakSelf.pictureArr.count;i++){
//            if ([weakSelf.pictureArr[i] isKindOfClass:[NSString class]]){
//                [self.pictureArr removeObjectAtIndex:i];
//            }
//        }
//        [weakSelf.pictureArr addObject:@"icon_push_picture"];
//        [weakSelf.collectionView reloadData];
//         
//    }];
//    
//    [[NERUtils getVisibleViewController] presentViewController:picturePickerVC animated:YES completion:nil];
//}



//压缩图片
-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return image;
}

- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length > 300){
        textView.text = [textView.text substringToIndex:300];
    }
    self.editView.currentText.text = [NSString stringWithFormat:@"%lu/300",(unsigned long)textView.text.length];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


#pragma mark ---ALVPushCollectionViewCellDelegate
- (void)deleteCellImage:(NSInteger)row {
    [self.pictureArr removeObjectAtIndex:row];
    self.cellNumber --;
    [self.collectionView reloadData];
}

- (IBAction)clickBackBtn:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)clickSaveBtn:(id)sender {
    
    if (self.editView.textView.text == nil|| [self.editView.textView.text isEqualToString: @""]) {
        [ASHUD showWithText:@"You have unfilled content！" afterDelay:2];
        return;
    }
    if (self.textFiled.text == nil|| [self.textFiled.text isEqualToString: @""]) {
        [ASHUD showWithText:@"You have unfilled content！" afterDelay:2];
        return;
    }
    
    if (self.pictureArr.count>1) {
        [self.pictureArr removeLastObject];//删掉最后一个的默认选择图
        for (UIImage *newimg in self.pictureArr) {
            NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            NSString *fileName = [NSString stringWithFormat:@"image_%f.png", [NSDate date].timeIntervalSince1970];
            NSString *filePath = [documentDirectory stringByAppendingPathComponent:fileName];
            NSData *imageData = UIImagePNGRepresentation(newimg);
            // 或者，如果需要JPEG格式
            // NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
            [imageData writeToFile:filePath atomically:YES];
            [self.fileNameArr addObject:fileName];
        }
    }else{
        [ASHUD showWithText:@"You have unfilled content！" afterDelay:2];
        return;
    }
    

    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    int timestamp = timeInterval;
    NSLog(@"%d", timestamp);
    NSDictionary *  params = @{
          @"content": self.editView.textView.text,
          @"title": self.textFiled.text,
          @"avatar": [BJUserManager sharedManager].userInfoData.avatarUrl,
          @"nickname": [BJUserManager sharedManager].userInfoData.nickname,
          @"imageArrStr": [self.fileNameArr componentsJoinedByString:@","],
          @"userId": [NSString stringWithFormat:@"%d",timestamp],

        };
    
    [ASHUD showASLoading];

    [[BJPushFMDBManger sharedManager] insertData:params];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ASHUD hideHUD];
        [ASHUD showWithText:@"posted Successfully" afterDelay:2];

        
        [self dismissViewControllerAnimated:YES completion:nil];
    });

    
}



@end
